const query = require('../queryEngine/index.js');
const tool = require('../common/index.js');
var crypto = require('crypto');

function getRandomString(length) {
    let num = Math.ceil(length / 13);
    let str = '';
    for (let i = 1; i <= num; i++) {
        str += Math.random().toString(16).substr(2);
    }
    return str.substr(0, length);
}

module.exports = {
    'POST /login': async (ctx, next) => {
        let username, encryptedPassword;
        ctx.response.type = 'application/x-www-form-urlencoded';
        let body = ctx.request.body;
        username = body.username;
        let hmac = crypto.createHmac('sha256', 'secret-key');
        hmac.update(body.password);
        encryptedPassword = hmac.digest('hex');
        let result = await query.user({where: {username: username}});
        if (result.length == 0) {
            ctx.response.status = 481;
            ctx.response.message = 'error:no such user';
        } else if (result.length!=1){
            ctx.response.status = 522;
            ctx.response.message = 'error:multiple user found';
        }else{
            for (let item of result) {
                let userInfo = item.dataValues;
                let realPassword = userInfo.password;
                if (realPassword == encryptedPassword) {
                    let token = getRandomString(120);
                    item.token = token;
                    item.lastTime = new Date();
                    await item.save();
                    ctx.response.body = {
                        errorCode: 0,
                        token: token
                    };
                } else {
                    ctx.response.status = 482;
                    ctx.response.message = 'error:invalid username or password';
                }
            }
        }
    },
    'GET /token': async (ctx, next) => {
        ctx.response.type = 'application/json';
        let res = await query.user({where: tool.parseUrl(ctx.request.url)});
        if (res[0]){
            ctx.response.body = res;
        }else{
            ctx.response.status = 521;
            ctx.response.message = 'login status overdue, please log in again'
        }
    },
    'POST /createUser': async (ctx, next) => {
        let encryptedPassword;
        ctx.response.type = 'application/x-www-form-urlencoded';
        let body = ctx.request.body;
        let hmac = crypto.createHmac('sha256', 'secret-key');
        hmac.update(body.password);
        encryptedPassword = hmac.digest('hex');
        let token = getRandomString(120);
        let result = await query.user({where: {username: body.username}});
        if (result.length == 0) {
            await query.createUser({
                username: body.username,
                password: encryptedPassword,
                type: body.type,
                token: token,
                email: body.email,
                nickname: body.nickname,
                avatar:body.avatar
            }).then(() => {
                ctx.response.body = {
                    errorCode: 0,
                    errorMsg: '注册成功',
                    token: token
                };
            }).catch((err) => {
                ctx.response.status = 488;
                ctx.response.message = err;
            });
        } else {
            ctx.response.status = 490;
            ctx.response.message = 'error: username exsited, please change a new one';
        }
    },
    'POST /changeUserPwd': async (ctx, next) => {
        ctx.response.type = 'application/x-www-form-urlencoded';
        let body = ctx.request.body;
        let username = body.username;
        let hmac = crypto.createHmac('sha256', 'secret-key');
        hmac.update(body.oldPassword);
        let password = hmac.digest('hex');
        hmac = crypto.createHmac('sha256', 'secret-key');
        hmac.update(body.newPassword);
        let newPassword = hmac.digest('hex');
        await query.user({where: {username: username, password: password}}).then(async (res) => {
            for (let item of res) {
                item.password = newPassword;
                await item.save();
                ctx.response.body = {
                    errorCode: 0,
                    errorMsg: '成功'
                };
            }
        }).catch(err => {
            ctx.response.status = 489;
            ctx.response.message = err.name;
        });
    },
    'GET /editUserInfo': async (ctx, next) => {
        ctx.response.type = 'application/json';
        let requestBody = tool.parseUrl(decodeURIComponent(ctx.request.url));
        await query.editUserInfo({
            nickname: requestBody.nickname,
            email: requestBody.email,
            avatar:requestBody.avatar
        }, {where: {id: requestBody.id}}).then(() => {
            ctx.response.body = {
                errorCode: 0,
                errorMsg: '成功'
            };
        }).catch(err=>{
            ctx.response.status = 491;
            ctx.response.message = err.name;
        })
    }
};